import { Injectable } from '@nestjs/common';
import { Request } from 'express';

/**
 * 上下文服务
 * 提供请求上下文管理功能
 */
@Injectable()
export class ContextService {
  private readonly contextMap = new Map<string, any>();

  /**
   * 设置上下文数据
   */
  setContext(key: string, value: any) {
    this.contextMap.set(key, value);
  }

  /**
   * 获取上下文数据
   */
  getContext<T = any>(key: string): T | undefined {
    return this.contextMap.get(key);
  }

  /**
   * 清除上下文数据
   */
  clearContext(key?: string) {
    if (key) {
      this.contextMap.delete(key);
    } else {
      this.contextMap.clear();
    }
  }

  /**
   * 从请求中提取用户信息
   */
  getUserFromRequest(request: Request) {
    return (request as any).user;
  }

  /**
   * 从请求中提取站点信息
   */
  getSiteFromRequest(request: Request) {
    return (request as any).site;
  }

  /**
   * 获取当前用户 ID
   */
  getCurrentUserId(request: Request): number | undefined {
    const user = this.getUserFromRequest(request);
    return user?.userId;
  }

  /**
   * 获取当前站点 ID
   */
  getCurrentSiteId(request: Request): number | undefined {
    const site = this.getSiteFromRequest(request);
    return site?.siteId;
  }

  /**
   * 获取客户端 IP
   */
  getClientIp(request: Request): string {
    return (
      (request.headers['x-forwarded-for'] as string) ||
      (request.headers['x-real-ip'] as string) ||
      request.connection.remoteAddress ||
      request.socket.remoteAddress ||
      '127.0.0.1'
    );
  }

  /**
   * 获取用户代理
   */
  getUserAgent(request: Request): string {
    return request.headers['user-agent'] || '';
  }
}
